package com.yx.cloud.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.iot.common.utils.LogUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.NetworkInterface;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 创建时间 : 2017/9/12.
 * 创建人 :
 * 功能描述 : String字符串的转换工具类
 */

public class StringUtils {
    private static final String TAG = "StringUtils";
    private static long lastClickTime;
    private Context mContext;

    public StringUtils(Context context) {
        mContext = context;
    }

    public static String stringReplace(String str) {
        //去掉" "号
//        String mSSIDName = str.replace("\"", "");
        return str.replace(":", "-");
    }

    /**
     * 字符串转换为16进制字符串
     *
     * @param s
     * @return
     */
    public static String stringToHexString(String s) {
        String hexString = "0123456789abcdef";
        //根据默认编码获取字节数组
        byte[] bytes = s.getBytes();
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        //将字节数组中每个字节拆解成2位16进制整数
        for (int i = 0; i < bytes.length; i++) {
            sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
            sb.append(hexString.charAt((bytes[i] & 0x0f)));
        }
        return sb.toString();


    }

    public static String hexStr2Str(String hexStr) {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;

        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    /**
     * 十六进制转换字符串
     */
//    public static String hexStr2Str(String bytes) {
//        String hexString = "0123456789abcdef";
//        ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);
//        //将每2位16进制整数组装成一个字节
//        for (int i = 0; i < bytes.length(); i += 2)
//            baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes.charAt(i + 1))));
//        return new String(baos.toByteArray());
//    }

    /**
     * 判断字符串中是否包含中文
     *
     * @param str 待校验字符串
     * @return 是否为中文
     * @warn 不能校验是否为中文标点符号
     */
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }


    /**
     * 现在不能一直点击按钮
     *
     * @return
     */
    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        Log.i(TAG, ".......>" + timeD);
        if (0 < timeD && timeD < 2000) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 获取一个10位的时间戳
     *
     * @return
     */
    public static String getTime() {
        //获取系统时间的10位的时间戳
        long time = System.currentTimeMillis();
        String str = String.valueOf(time);
        return str;
    }

    /**
     * 精确到毫秒的时间戳
     */
    public static String dateToStamp() {
        Date d = new Date();

        String timestamp = String.valueOf(d.getTime());

        String value = String.valueOf(Long.valueOf(timestamp));
        return value;
    }

    /**
     * 时间转为时间戳
     *
     * @param time "2016-01-12 12:05:00"
     * @return
     */
    public static Integer StringToTimestamp(String time) {


        int times = 0;
        try {
            times = (int) ((Timestamp.valueOf(time).getTime()) / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (times == 0) {
            System.out.println("String转10位时间戳失败");
        }
        return times;

    }

    /**
     * 时间戳为时间转
     *
     * @param time "1654756552"
     * @return
     */
    public static String timeStamp2Date(long time, String format) {
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(time * 1000));
    }

    /**
     * 把中文字符串转换为十六进制Unicode编码字符串
     *
     * @param str 中文字符串
     * @return
     */
    public static String str2HexStr(String str) {

        char[] chars = "0123456789abcdef".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;

        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
            sb.append(' ');
        }
        return sb.toString().trim();
    }

    /**
     * 字符串是否为json数据格式
     *
     * @param json
     * @return
     */
    public static boolean isJson(String json) {
        try {
            JSONObject jsonStr = JSONObject.parseObject(json);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 字符串是否为json数据格式
     *
     * @param json
     * @return
     */
    public static JSONObject toJson(String json) {
        try {

            return JSONObject.parseObject(json);
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * List集合 数据去重复
     *
     * @param arr
     * @return
     */
    public static List getList(List arr) {

        List list = new ArrayList();
        list.clear();
        Iterator it = arr.iterator();

        while (it.hasNext()) {

            Object obj = (Object) it.next();

            if (!list.contains(obj)) {                //不包含就添加

                list.add(obj);
            }
        }
        return list;
    }

    /**
     * 把十六进制Unicode编码字符串转换为中文字符串, 将\u848B\u4ECB\u77F3转化成蒋介石，注意格式
     *
     * @param str eg:\u848B\u4ECB\u77F3
     * @return 蒋介石
     */
    public static String unicodeToString(String str) {

        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");

        Matcher matcher = pattern.matcher(str);

        char ch;

        while (matcher.find()) {

            ch = (char) Integer.parseInt(matcher.group(2), 16);

            str = str.replace(matcher.group(1), ch + "");

        }

        return str;
    }

    /**
     * 得到加冒号 或 取去掉冒号的Mac地址
     *
     * @param mac
     * @return
     * @author YOLANDA
     */
    public static String getMac(String mac) {
        String[] macs = new String[6];
        for (int i = 0; i <= 5; i++) {
            macs[i] = mac.substring(i * 2, i * 2 + 2);
        }
        mac = macs[0];
        for (int i = 1; i < macs.length; i++) {
            mac += ":" + macs[i];
        }
        return mac;
    }

    /**
     * 这是使用adb shell命令来获取mac地址的方式
     *
     * @return
     */
    public static String getMac() {
        String macSerial = null;
        String str = "";

        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (IOException ex) {
            // 赋予默认值
            ex.printStackTrace();
        }
        return macSerial;
    }

    /**
     * 校验MAC地址格式
     *
     * @param mac
     * @return
     */
    public static boolean macCheck(String mac) {
        //1.Mac地址以空格,"-",":"分开
        String check = "^([0-9a-fA-F]{2})(([/\\s:-][0-9a-fA-F]{2}){5})$";
        //2.中间没有任何符号
//        String check = "^([0-9a-fA-F]{2})(([0-9a-fA-F]{2}){5})$";
        Pattern pattern = Pattern.compile(check);
        Matcher matcher = pattern.matcher(mac);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }

    private static String getAdressMacByInterface() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (nif.getName().equalsIgnoreCase("wlan0")) {
                    byte[] macBytes = nif.getHardwareAddress();
                    if (macBytes == null) {
                        return "";
                    }

                    StringBuilder res1 = new StringBuilder();
                    for (byte b : macBytes) {
                        res1.append(String.format("%02X:", b));
                    }

                    if (res1.length() > 0) {
                        res1.deleteCharAt(res1.length() - 1);
                    }
                    return res1.toString();
                }
            }

        } catch (Exception e) {
            Log.e("MobileAcces", "Erreur lecture propriete Adresse MAC ");
        }
        return null;
    }


    private static String crunchifyGetStringFromStream(InputStream crunchifyStream) throws
            IOException {
        if (crunchifyStream != null) {
            Writer crunchifyWriter = new StringWriter();

            char[] crunchifyBuffer = new char[2048];
            try {
                Reader crunchifyReader = new BufferedReader(new InputStreamReader(crunchifyStream, "UTF-8"));
                int counter;
                while ((counter = crunchifyReader.read(crunchifyBuffer)) != -1) {
                    crunchifyWriter.write(crunchifyBuffer, 0, counter);
                }
            } finally {
                crunchifyStream.close();
            }
            return crunchifyWriter.toString();
        } else {
            return "No Contents";
        }
    }

    //将获取的int（如：1866655656）转为真正的ip地址,参考的网上的，修改了下
    public static String intToIp(int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 24) & 0xFF);
    }

    int parseInt;

    /**
     * String 转 Int
     *
     * @param string
     * @return
     */
    public static int strConversionInt(String string) {
        int parseInt = 0;
        try {
            parseInt = Integer.parseInt(string);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return parseInt;

    }


    //判断字符串是不是以数字开头
    public static boolean isStartWithNumber(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str.charAt(0) + "");
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }


    //MD5加密
    public static String toMD5(String text) throws NoSuchAlgorithmException {
        //获取摘要器 MessageDigest
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        //通过摘要器对字符串的二进制字节数组进行hash计算
        byte[] digest = messageDigest.digest(text.getBytes());

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < digest.length; i++) {
            //循环每个字符 将计算结果转化为正整数;
            int digestInt = digest[i] & 0xff;
            //将10进制转化为较短的16进制
            String hexString = Integer.toHexString(digestInt);
            //转化结果如果是个位数会省略0,因此判断并补0
            if (hexString.length() < 2) {
                sb.append(0);
            }
            //将循环结果添加到缓冲区
            sb.append(hexString);
        }
        //返回整个结果
        return sb.toString();
    }

    public static String beanToJson(Object bean) {
        Gson gson = new Gson();
        String jsonStr = gson.toJson(bean);
        System.out.println(jsonStr);
        return jsonStr;
    }

    public static String byteToString(byte[] data) {
        int index = data.length;
        for (int i = 0; i < data.length; i++) {
            if (data[i] == 0) {
                index = i;
                break;
            }
        }
        byte[] temp = new byte[index];
        Arrays.fill(temp, (byte) 0);
        System.arraycopy(data, 0, temp, 0, index);
        String str;
        try {
            str = new String(temp, "utf-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }
        return str;
    }

    /**
     * 字节数组转换为十六进制字符串
     *
     * @param b byte[] 需要转换的字节数组
     * @return String 十六进制字符串
     */
    public static String byte2hex(byte b[]) {
        if (b == null) {
            throw new IllegalArgumentException(
                    "Argument b ( byte array ) is null! ");
        }
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0xff);
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    }

    public static String getLocationCity(Context context) throws IOException {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        String provider = locationManager.getBestProvider(criteria, true);
        // 检查是否获取到了位置提供器
        if (provider != null && !provider.equals("")) {
            @SuppressLint("MissingPermission") Location location = locationManager.getLastKnownLocation(provider);
            if (location != null) {
                Geocoder geocoder = new Geocoder(context, Locale.getDefault());
                List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                LogUtils.i("当前所在城市 111 " + new Gson().toJson(addresses));
                if (addresses != null && addresses.size() > 0) {
                    String city = addresses.get(0).getLocality();
                    LogUtils.i("当前所在城市 " + city);
                    // 在这里处理获取到的城市信息
                    return city;
                }
            }
        }
        return "";
    }
}
